
import { memo, ReactChild, useCallback } from 'react'
// @ts-ignore
import Styles from './index.scss'
import imageFormat from '@utils/oss'
import LazyLoad from 'react-lazyload';
import Router from 'next/router'

export enum ShowModel {
  lfit = 'imageLfit',
  mfit = 'imageMfit',
  fill = 'imageFill'
}

interface PropsInterface {
  url: string,
  model: ShowModel,
  width: number
  height: number
  lazyHeight?: number
  // 子元素
  children?: ReactChild
  className?: string
  toPath?: string
  onClick?: (url: string) => void
  // 是否懒加载
  lazyLoad: boolean
  // 是否自动设置图片大小
  resize: boolean
  // 是否是圆形
  round: boolean
}

const WImage = (props: PropsInterface) => {

  const { url, model, width, height, className, lazyHeight, children, lazyLoad, resize, round } = props

  const fomUrl = resize ? imageFormat[model](url, width, height) : url

  const imgClick = useCallback(() => {
    props.onClick && props.onClick(url)
    props.toPath && Router.push(props.toPath)
  }, [])

  const imageDom = useCallback(() => {
    return (
      <div
        className={`${Styles['w-image']} ${model === ShowModel.fill ? 'w-image-fill' : 'w-image-fit'} ${className || ''} ${ round ? 'w-round' : '' }`}
        style={{ backgroundImage: `url(${fomUrl})`, width: `${width}px`, height: `${height}px` }}
        onClick={imgClick}
      >
        {children}
      </div>
    )
  }, [model, className, fomUrl, width, height, children])

  return lazyLoad ? <LazyLoad height={lazyHeight === undefined ? height : lazyHeight}>
    {imageDom()}
  </LazyLoad> : imageDom()
}

WImage.defaultProps = {
  model: ShowModel.fill,
  onClick: () => { },
  lazyLoad: true,
  resize: true,
  round: false
};

export default memo(WImage)